﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Ornament.NHibernates.Configurations
{
    /// <summary>
    /// 对应Nhibernate 配置文件中 Property 标记。
    /// </summary>
    public abstract class PropertyContainer
    {
        private readonly XElement settingElement;
        private readonly XNamespace xNamespace = "urn:nhibernate-configuration-2.2";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sessionFactoryElement"></param>
        protected PropertyContainer(XElement sessionFactoryElement)
        {
            settingElement = sessionFactoryElement;
        }

        protected void Delete(string key)
        {
            XElement result = this.FindElement(key);
            if (result != null)
            {
                result.Remove();
            }
        }

        /// <summary>
        /// Gets the property value. default return null;
        /// </summary>
        /// <param name="key">The key. the value belong to name attribute</param>
        /// <returns>return element propety 's inner text which 'name' attribute,
        /// it's value is equal the key,couldn't find ,return null</returns>
        protected string GetPropertyValue(string key)
        {
            XElement result = this.FindElement(key);
            if (result == null)
                return null;
            return result.Value;
        }

        protected void SetPropertyValue(string key, string value)
        {
            XElement result = FindElement(key);
            if (result == null)
            {
                var newProperty = new XElement(xNamespace + "property");
                newProperty.Value = value;
                var propertyName = new XAttribute("name", key);
                newProperty.Add(propertyName);

                settingElement.AddFirst(newProperty);
            }
            else
                result.Value = value;
        }

        protected bool RemoveProperty(string key)
        {
            var element = FindElement(key);
            if (element != null)
            {
                element.Remove();
                return false;
            }
            return false;

        }

        protected XElement FindElement(string nameAttributeValue)
        {
            IEnumerable<XElement> property = from prop in settingElement.Elements(xNamespace + "property")
                                             where prop.Attribute("name") != null && prop.Attribute("name").Value == nameAttributeValue
                                             select prop;
            XElement result = property.SingleOrDefault();
            if (result == null || result.IsEmpty)
                return null;
            return result;
        }
    }
}